let localGroupConfig = {
    isOpenRecommond: true,
    recommondRound: 5,
    recommondRewardRound: 3,
    isOpenGroupRandom: true,
    isOpenLevelRandom: true,
    randomLevelNum: 2,
    levelGroups: [
        {
            name: "怀旧", weight: 0, id:1, items: [
                { tag: 722, weight: 10, id:1 },
                { tag: 721, weight: 10, id:2 },
                { tag: 720, weight: 10, id:3 },
                { tag: 719, weight: 10, id:4 }
            ]
        },
        {
            name: "微恐", weight: 10, id:2, items: [
                { tag: 287, weight: 10, id:1 },
                { tag: 286, weight: 10, id:2 },
                { tag: 285, weight: 10, id:3 },
                { tag: 284, weight: 10, id:4 }
            ]
        }
    ]
 };
let localGroupList = localGroupConfig.levelGroups;

let currentGroupData = null;
let allGroup = {};

function updateGroupList() {
    var group_list = document.getElementById("group-list");
    if (group_list.innerHTML == "") {
        initGroupList();
    }
    group_list.innerHTML = "";
    for (let i = 0; i < localGroupList.length; i++) {
        const groupData = localGroupList[i];
        allGroup[groupData.name] = groupData;
        const listItem = document.createElement("li");
        listItem.style = "display: flex;flex-direction: row;";
        listItem.setAttribute("data-index", i);
        listItem.setAttribute("data-item", groupData.name);

        //分组名称
        const label = document.createElement("label");
        label.className = "level-title";
        label.textContent = groupData.name;
        label.style.pointerEvents = "none";
        listItem.appendChild(label);

        const div = document.createElement("div");
        div.style.flex = 1;
        div.style.pointerEvents = "none";
        listItem.appendChild(div);

        //权重
        const weightLabel = document.createElement("label");
        weightLabel.textContent = '权重:';
        listItem.append(weightLabel);
        const weightInput = document.createElement("input");
        weightInput.className = "input-number";
        weightInput.step = 1;
        weightInput.min = 0;
        weightInput.max = 100;
        weightInput.style.width = "40px";
        weightInput.style.marginLeft = "5px";
        weightInput.type = "number";
        weightInput.value = Number(groupData.weight);
        weightInput.onchange = (ev) => {
            let index = ev.target.parentElement.getAttribute("data-index");
            localGroupList[index - 1].weight = Number(ev.target.value);
        }
        listItem.appendChild(weightInput);
        group_list.appendChild(listItem);

        if (!currentGroupData && i == 0) {
            onSelectGroup(listItem);
        }else if(currentGroupData && currentGroupData.name == groupData.name){
            currentGroupData = null;
            onSelectGroup(listItem);
        }
    }
}

function initGroupList() {
    let sortable_list = document.getElementById("group-list")
    new Sortable(sortable_list, { name:"group",
        pull: false,
        put: false,
        animation: 150, // Animation speed in milliseconds
        onEnd: onGroupEndDrag,
    });
    sortable_list.addEventListener('click', function (event) {
        const target = event.target;
        if (target.tagName === 'LI') {
            onSelectGroup(target);
            sortable_list.focus();
        }
    });

    sortable_list.addEventListener('keydown', function (event) {
        if(event.target != sortable_list){
            return;
        }
        const keyCode = event.keyCode || event.which;
        if (keyCode === 46 || keyCode === 8) {
            // 获取选中的项
            let listItems = document.querySelectorAll("#group-list li");
            const selectedItems = Array.from(listItems).filter(item => item.classList.contains('li-selected'));
            selectedItems.forEach(item => item.remove());
            listItems = document.querySelectorAll("#group-list li");
            onSelectGroup(listItems.length ? listItems[0] : null);
            onGroupEndDrag();
        }
    });
}

function onSelectGroup(listItem) {
    if(!listItem){
        currentGroupData = null;
        updateGroupLevelList();
        return;
    }
    var groupName = listItem.getAttribute("data-item");
    if (!currentGroupData) {
        currentGroupData = allGroup[groupName];
        listItem.classList.add('li-selected');
        updateGroupLevelList();
        return;
    }
    if (currentGroupData.name != groupName) {
        const listItems = document.querySelectorAll("#group-list li");
        for (let i = 0; i < listItems.length; i++) {
            const element = listItems[i];
            let itemName = element.getAttribute("data-item");
            if (itemName != groupName) {
                element.classList.remove('li-selected');
            }
        }
        currentGroupData = allGroup[groupName];
        listItem.classList.add('li-selected');
        updateGroupLevelList();
    }
}

function onGroupEndDrag() {
    localGroupList.length = 0;
    const listItems = document.querySelectorAll("#group-list li");
    for (let i = 0; i < listItems.length; i++) {
        const element = listItems[i];
        var groupName = element.getAttribute("data-item");
        allGroup[groupName].id = i + 1;
        localGroupList.push(allGroup[groupName]);
    }
    updateGroupList();
    console.log("保存到本地", localGroupList)
    // localStorage.setItem("export_list", JSON.stringify(exportList));
}

function onCreatGroup(){
    let newGroupName = document.getElementById('group-name-input').value;
    if(!newGroupName){
        showToast("请输入组名");
        return
    }
    let hasExist = localGroupList.filter(value=>value.name==newGroupName);
    if(hasExist && hasExist.length){
        showToast("有重名的组："+ newGroupName);
        return
    }
    let newGroupData = {name: newGroupName, weight: 0, items: []};
    localGroupList.push(newGroupData);
    currentGroupData = newGroupData;
    updateGroupList();
    console.log("保存到本地")
}


function updateGroupLevelList() {
    console.log("updateGroupLevelList")
    var group_level_list = document.getElementById("group-level-list");
    if(!currentGroupData){
        group_level_list.innerHTML = "";
        return;
    }
    if (group_level_list.innerHTML == "") {
        initGroupLevelList();
    }
    group_level_list.innerHTML = "";
    let currentLevelList = currentGroupData.items;
    let allLevelDict = getAllLevels();
    for (let i = 0; i < currentLevelList.length; i++) {
        const levelData = currentLevelList[i];
        const listItem = document.createElement("li");
        listItem.style = "display: flex;flex-direction: row;";
        listItem.setAttribute("data-index", i + 1);
        listItem.setAttribute("data-item", JSON.stringify(levelData));

        //关卡名称
        const label = document.createElement("label");
        label.className = "level-title";
        label.textContent = levelData.tag + ":" + (allLevelDict[levelData.tag] && allLevelDict[levelData.tag]['subTitle'] || `未找对应关卡`);
        label.style.pointerEvents = "none";
        listItem.appendChild(label);

        const div = document.createElement("div");
        div.style.flex = 1;
        div.style.pointerEvents = "none";
        listItem.appendChild(div);

        //权重
        const weightLabel = document.createElement("label");
        weightLabel.textContent = '权重:';
        listItem.append(weightLabel);
        const weightInput = document.createElement("input");
        weightInput.className = "input-number";
        weightInput.step = 1;
        weightInput.min = 0;
        weightInput.max = 100;
        weightInput.style.width = "40px";
        weightInput.style.marginLeft = "5px";
        weightInput.type = "number";
        weightInput.value = Number(levelData.weight);
        weightInput.onchange = (ev) => {
            let index = JSON.parse(ev.target.parentElement.getAttribute("data-index"));
            currentGroupData.items[index - 1].weight = Number(ev.target.value);
            ev.target.parentElement.setAttribute("data-item", JSON.stringify(currentGroupData.items[index - 1]));
        }
        listItem.appendChild(weightInput);
        group_level_list.appendChild(listItem);
    }
}


var hasInitGroupLevelList = false;

function initGroupLevelList() {
    if(hasInitGroupLevelList){
        return;
    }
    hasInitGroupLevelList = true;
    let sortable_list = document.getElementById("group-level-list")
    new Sortable(sortable_list, {
        group: 'shared',
        animation: 150, // Animation speed in milliseconds
        onEnd: onGroupLevelEndDrag,
        onAdd: onGroupLevelEndDrag,
    });

    sortable_list.addEventListener('click', function (event) {
        const target = event.target;
        if (target.tagName === 'LI') {
            target.classList.toggle('li-selected');
            sortable_list.focus();
        }
    });

    sortable_list.addEventListener('keydown', function (event) {
        if(event.target != sortable_list){
            return;
        }
        const keyCode = event.keyCode || event.which;
        if (keyCode === 46 || keyCode === 8) {
            // 获取选中的项
            const listItems = document.querySelectorAll("#group-level-list li");
            const selectedItems = Array.from(listItems).filter(item => item.classList.contains('li-selected'));
            selectedItems.forEach(item => item.remove());
            onGroupLevelEndDrag();
        }
    });
}

function onGroupLevelEndDrag() {
    currentGroupData.items.length = 0;
    const listItems = document.querySelectorAll("#group-level-list li");
    for (let i = 0; i < listItems.length; i++) {
        const element = listItems[i];
        var data = JSON.parse(element.getAttribute("data-item"));
        if(data.weight == null){
            data = { tag: data.tag, weight: 0 };
            element.setAttribute("data-item", JSON.stringify(data));
        }
        data.id = i + 1;
        currentGroupData.items.push(data)
    }
    // const groupListItems = document.querySelectorAll("#group-list li");
    // const selectedItems = Array.from(groupListItems).filter(item => item.classList.contains('li-selected'));
    // selectedItems.forEach(item => {
    //     item.setAttribute("data-item", JSON.stringify(currentGroupData));
    // });

    console.log("保存到本地", localGroupList);
    updateGroupLevelList();
}

function onSwitchChanged(event) {
    let value = event.target.checked;
    localGroupConfig[event.target.id] = value;
    console.log(event.target.id, value)
}

function onInputChanged(event) {
    let value = event.target.value;
    localGroupConfig[event.target.id] = value;
    console.log(event.target.id, value)
}

function exportGroupData() {
    console.log("打印最新推荐配置:", localGroupConfig);
    
    let allLevelDict = getAllLevels();
    for (let group = 0; group < localGroupList.length; group++) {
      const groupInfo = localGroupList[group];
      let countDict = {};
      for (let i = 0; i < groupInfo.items.length; i++) {
        const levelInfo = groupInfo.items[i];
        countDict[levelInfo.tag] = countDict[levelInfo.tag] || 0;
        countDict[levelInfo.tag] += 1;
        if(countDict[levelInfo.tag] >= 2){
          showToast(`【${groupInfo.name}】组中《${allLevelDict[levelInfo.tag].subTitle}》关卡重复`)
          return;
        }
      }
    }
    
    let jsonString = JSON.stringify(localGroupConfig);
    const dataURL = 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonString);
    
    const a = document.createElement('a');
    a.href = dataURL;
    let flag = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    flag = flag.replace(/:/g, ".").replace(/\//g, ".").replace(" ", "_")
    // let md5 = saveLevelOrderToLocal();
    a.download = `recommend_${flag}.json`;
    a.click();
    a.remove();
    jsonString = jsonString.replace(/"/g, "'");
    navigator.clipboard.writeText(`版本:${flag}\n${jsonString}`);
    saveToLocal();
    initExportGroupSelect();
    updateGroupList();
    updateGroupLevelList();
    showToast("成功！配置已拷贝到粘贴贴面板, Ctrl+V发送给程序。");
}

function saveToLocal() {
    let exportList = localStorage.getItem("export_group_list") || "[]";
      exportList = JSON.parse(exportList);
      exportList.push({time:Date.now(), config:localGroupConfig});
      if(exportList.length > 10){
        exportList.splice(0, 10-exportList.length)
      }
      localStorage.setItem("export_group_list", JSON.stringify(exportList));
}

function initExportGroupSelect() {
    let exportList = localStorage.getItem("export_group_list") || "[]";
    exportList = JSON.parse(exportList);
    if(exportList.length == 0) return;
    const selectElement = document.getElementById("export-group-select");
    selectElement.innerHTML = "";
    for (let i = 0; i < exportList.length; i++) {
      const exportInfo = exportList[i];
      const newOption = document.createElement("option");
      // newOption.value = JSON.stringify(exportInfo);
      newOption.selected = i == exportList.length - 1;
      let exportDate = new Date(exportInfo.time);
      newOption.textContent = `${exportDate.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`;
      selectElement.appendChild(newOption);
    }
    localGroupConfig = exportList[exportList.length - 1].config;
    localGroupList = localGroupConfig.levelGroups;
    currentGroupData = null;
    selectElement.addEventListener("change", onExportGroupSelectChanged);
  }

  function onExportGroupSelectChanged() {
    let localExportList = localStorage.getItem("export_group_list") || "[]";
    localExportList = JSON.parse(localExportList);
    const selectElement = document.getElementById("export-group-select");
    const selectedIndex = selectElement.selectedIndex;
    if(selectedIndex == -1) {
      return 
    }
    localGroupConfig = localExportList[selectedIndex].config;
    localGroupList = localGroupConfig.levelGroups;
    currentGroupData = null;
    updateGroupList();
  }

function importGroupData() {
    const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = function (event) {
          const jsonStr = event.target.result;
          fileInput.remove();
          const jsonData = JSON.parse(jsonStr);
          console.log("导入：", jsonData);
          localGroupConfig = jsonData;
          localGroupList = localGroupConfig.levelGroups;
          updateGroupList();
          updateSwitches();
          showToast("数据导入成功!");
        };
        reader.readAsText(file);
      });
      fileInput.click();
}

function updateSwitches() {
    let element = document.getElementById('isOpenRecommond');
    element.checked = localGroupConfig.isOpenRecommond;

    element = document.getElementById('isOpenGroupRandom');
    element.checked = localGroupConfig.isOpenGroupRandom;

    element = document.getElementById('isOpenLevelRandom');
    element.checked = localGroupConfig.isOpenLevelRandom;

    element = document.getElementById('recommondRound');
    element.value = localGroupConfig.recommondRound;

    element = document.getElementById('recommondRewardRound');
    element.value = localGroupConfig.recommondRewardRound;

    element = document.getElementById('randomLevelNum');
    element.value = localGroupConfig.randomLevelNum;
}